import hashlib
import json
import os
from tkinter import *
import requests
import time
from datetime import datetime
import random
# 循环延迟
LoopDelay = 0.3

def generate_nonce_str(length=10):
    # 定义字符集，包含大小写字母和数字
    chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    nonce_str = ""
    for _ in range(length):
        # 随机选择一个字符添加到结果中
        nonce_str += chars[random.randint(0, 61)]
    return nonce_str

# 账号密码登陆
def LoginHLX(username, password, Type=None):
    if Type:
        Web = "tool_web"
        print("登陆葫芦侠")
    else:
        Web = "floor_web"
        print("登陆葫芦侠三楼")

    # MD5加密密码
    MdPassword = hashlib.md5(password.encode('utf-8')).hexdigest()
    # sign计算
    sign = "account" + username + "device_code[d]b305cc73-8db8-4a25-886f-e73c502b1e99password" + MdPassword + "voice_codefa1c28a5b62e79c3e63d9030b6142e4b"
    sign = hashlib.md5(sign.encode('utf-8')).hexdigest()
    # 提交地址
    url = f"http://floor.huluxia.com/account/login/ANDROID/4.1.8?platform=2&gkey=000000&app_version=4.3.0.4&versioncode=20141495&market_id={Web}&_key=&device_code=%5Bd%5Db305cc73-8db8-4a25-886f-e73c502b1e99&phone_brand_type=UN"
    # 登录提交数据
    data = {
        'account': username,
        'login_type': '2',
        'password': MdPassword,
        'sign': sign}
    # 协议头
    headers = {"User-Agent": "okhttp/3.8.1"}
    # 请求访问
    retu = requests.post(url=url, data=data, headers=headers)
    print(retu.text)
    retu.encoding = retu.apparent_encoding
    # json解析
    login_json = json.loads(retu.text)
    user = login_json['user']
    # 提取key数据和ID
    user_info = [user['userID'], login_json['_key']]

    return user_info


def login(username, password, tool_type=None, Path=None, LogUI=None):
    value = False
    if hasattr(username, 'get') and hasattr(password, 'get'):
        username = username.get()
        password = password.get()
        value = tool_type.get()

    IdAndKey = LoginHLX(username, password, value)
    # 检查目标路径是否存在，如果不存在则创建
    if not os.path.exists(os.path.dirname(Path)):
        os.makedirs(os.path.dirname(Path))
    else:
        # 将 default_value 保存到 d:/HLX/default.json 文件中
        with open(Path, "w") as f:
            json.dump({
                "Id": IdAndKey[0],
                "Key": IdAndKey[1]
            }, f)
    print("登陆成功", IdAndKey[1])

    LogUI.destroy()
    exit()


def LoginUI(Path):
    LogUI = Tk()

    LogUI.title("登陆")

    username_label = Label(LogUI, text="用户名：")
    username_label.grid(row=0, column=0, padx=10, pady=5, sticky=E)
    username_entry = Entry(LogUI)
    username_entry.grid(row=0, column=1, padx=10, pady=5)

    password_label = Label(LogUI, text="密码：")
    password_label.grid(row=1, column=0, padx=10, pady=5, sticky=E)
    password_entry = Entry(LogUI, show="*")
    password_entry.grid(row=1, column=1, padx=10, pady=5)

    switch_var = IntVar()
    switch = Checkbutton(LogUI, text="登陆到葫芦侠(取消勾选登陆到葫芦侠三楼)", variable=switch_var)
    switch.grid(row=3, columnspan=2, pady=10)
    login_button = Button(LogUI, text="登陆",
                          command=lambda: login(username_entry, password_entry, switch_var, Path, LogUI))
    login_button.grid(row=2, columnspan=2, pady=10)

    LogUI.mainloop()



MyKey = ""
userId = ""
file_path = 'D:/HLX/default.json'


def md5(param):
    m = hashlib.md5()
    b = param.encode(encoding='utf-8')
    m.update(b)
    passwd_md5 = m.hexdigest()
    return passwd_md5

# 检查Key是否有效
def checkKey(MyKey):
    url = f"http://floor.huluxia.com/account/security/info/ANDROID/4.2.2?_key={MyKey}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
    }

    response = requests.get(url, headers=headers)

    response_dict = response.json()

    if response_dict["status"]:
        print("已登录")
        return True
    else:
        print(response_dict["msg"])
        return False


def LoadJson(file_path, Key=None):
    try:
        with open(file_path, "r") as f:
            if f.read().strip():
                f.seek(0)
                data = json.load(f)
                if Key in data:
                    return data[Key]
                else:
                    print(KeyError)

    except (FileNotFoundError, KeyError):
        print(KeyError)


def main():

    global MyKey, userId

    print(f"当前Key和Id保存路径：{file_path}")
    print("删掉或更改即可重新登陆")

    # 驱赶次数，1或10
    frequency = int(input("输入单抽或五连抽(1或5)："))

    MyKey = LoadJson(file_path, "Key")
    userId = LoadJson(file_path, "Id")

    checkMyKey = checkKey(MyKey)
    if not checkMyKey:
        print("Key无效，请检查")
        LoginUI(file_path)



    url = "https://huodong.huluxia.com/api/view/activity/eleventhAnniversary/lottery"
    headers = {
        "Host": "huodong.huluxia.com",
        "Content-Length": "249",
        "Accept": "application/json, text/plain, */*",
        "User-Agent": "Mozilla/5.0 (Linux; Android 12; M2007J3SC Build/SKQ1.211006.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.72 MQQBrowser/6.2 TBS/046291 Mobile Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded",
        "Origin": "https://huodong.huluxia.com",
        "X-Requested-With": "com.huluxia.gametools",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer":f"https://huodong.huluxia.com/hlx-eleventh-anniversary/?versionCode=20141512&market_id=floor_web&userId={userId}&extraInfo=&device_code=%5Bw%5D02%3A00%3A00%3A00%3A00%3A00-%5Bi%5D863342023205943-%5Bs%5D89860052445246571934&_key={MyKey}",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }

    while True:
        # 获取当前时间的时间戳并取整
        current_timestamp = int(datetime.now().timestamp())
        nonceStr = generate_nonce_str(16)
        sign = md5(
            f'_key{MyKey}deviceCode[d]272188e5-dc54-44c1-adc3-b04b204ddc8cfrequency{frequency}nonceStr{nonceStr}timestamp{current_timestamp}ec6d94ff2f5e2b31382c23d3bdace5e9')

        data = {
            "_key": MyKey,
            "deviceCode": "[d]272188e5-dc54-44c1-adc3-b04b204ddc8c",
            "timestamp": current_timestamp,
            "nonceStr": nonceStr,
            "frequency": frequency,
            "sign": sign
        }
        response = requests.post(url, headers=headers, data=data)
        data = json.loads(response.text)
        print(data)

if __name__ == "__main__":
    main()
